IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[cms_sp_SiteAdminMapCreate]') AND type in (N'P', N'PC'))
	DROP PROCEDURE [dbo].[cms_sp_SiteAdminMapCreate]
GO
CREATE procedure [dbo].[cms_sp_SiteAdminMapCreate]
(
@Id [int] = null output,
@ParentNodeId [int] = null,
@NodeTitle nvarchar(150),
@NodeDescription nvarchar(500) = null,
@NodeUrl nvarchar(250),
@IsSpecial bit,
@IsVisible bit,
@IsCustom bit
)
as
declare @NodeTreeId hierarchyid
declare @NodeCount int
select @NodeCount = count(SiteAdminMapId) from [dbo].[SiteAdminMaps]
if @NodeCount = 0
begin
	set @NodeTreeId = null
end
if @ParentNodeId is null
begin
	set @NodeTreeId = hierarchyid::GetRoot()
end
else
begin
	declare @ParentNodeTreeId hierarchyid
	declare @NodeId hierarchyid
	select @ParentNodeTreeId = NodeTreeId from [dbo].[SiteAdminMaps]
	where SiteAdminMapId = @ParentNodeId
	select @NodeId = max(NodeTreeId) from [dbo].[SiteAdminMaps]
	where NodeTreeId.GetAncestor(1) = @ParentNodeTreeId
	set @NodeTreeId = @ParentNodeTreeId.GetDescendant(@NodeId, NULL)
end
insert into [dbo].[SiteAdminMaps]
(
[NodeTreeId],
[NodeTitle],
[NodeDescription],
[NodeUrl],
[IsSpecial],
[IsVisible],
[IsCustom]
)
values
(
@NodeTreeId,
@NodeTitle,
@NodeDescription,
@NodeUrl,
@IsSpecial,
@IsVisible,
@IsCustom
)
set @Id = SCOPE_IDENTITY()
return @Id


GO

